package com.mychoize.app.cricscore;

import java.util.List;

public class DataProvider {
	
	private DataReader reader;
	private DataConvertor convertor;
	private SimpleScoreService service;
	
	public DataProvider(){
		this.reader = new DataReader();
		this.convertor = new DataConvertor();
		this.service = new SimpleScoreService();
	}
	
	public List<Match> getMatches(){
		return convertor.getMatches(getMatchesFromLocalOrRemote());
	}
	
	public SimpleScore getScore(int id){
		
		SimpleScore score = MemCacheHelper.getInstane().getMatch(id);
		
		if(score == null){
			//System.out.println("Not found in memcache");
			String detail = reader.getScore(id);
			//System.out.println(detail);
			String livescore = getMatchesFromLocalOrRemote();
			score = convertor.getScore(detail, livescore,id);
			//System.out.println(score.getVersion());
			if(score.getVersion()>=0){
				//System.out.println("inseert or update");
				service.insertOrUpdateScore(score);
				MemCacheHelper.getInstane().putMatch(score);
				
			}
		}
		return score;
	}
	
	private String getMatchesFromLocalOrRemote(){
		String str = MemCacheHelper.getInstane().getLiveScore();
		if(str == null){
			str = reader.getMatches();
			MemCacheHelper.getInstane().setLiveScore(str);
		}
		return str;
	}
	
}
